package com.itheima.springbootwebtlias.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.anno.LogOperation;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.ClazzMapper;
import com.itheima.springbootwebtlias.mapper.StudentMapper;
import com.itheima.springbootwebtlias.pojo.Clazz;
import com.itheima.springbootwebtlias.pojo.ClazzQuerParam;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @LogOperation
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }

    @Override
    public List<Clazz> getAllClazz() {
        return clazzMapper.getAllClazz();
    }

    @Override
    public PageResult page(ClazzQuerParam clazzQuerParam) {
        //1.分页插件查询
        //1.启动
        PageHelper.startPage(clazzQuerParam.getPage(),clazzQuerParam.getPageSize());

        //2.调用持久层方法（强化版）
        Page<Clazz> clazzes = (Page<Clazz>) clazzMapper.selectbyCondition(clazzQuerParam);

        clazzes.getResult().stream().forEach( clazz -> {
            if(clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开课");
            }else if (clazz.getBeginDate().isBefore(LocalDate.now())){
                clazz.setStatus("已开课");
            }else {
                clazz.setStatus("今天开班");
            }
                }
        );
        //3.从翻页插件中增强的方法返回结果中，获取数据封装到PageResult
        PageResult pageResult = new PageResult(clazzes.getTotal(),clazzes.getResult());

        //3.封装返回结果
        return pageResult;
    }

    @Override
    public Clazz selectByIdClazz(Integer id) {

        Clazz list = clazzMapper.selectByIdClazz(id);

        return list;
    }

    @Override
    @LogOperation
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }

    @Override
    @LogOperation
    public void deleteByIdClazz(Integer id) {

        Integer count = studentMapper.deleteCountClazz(id);
        if (count != 0){
            throw new DeletionIsNotAllowed("当前班级存在学生，不允许删除");
        }

        clazzMapper.deleteByIdClazz(id);
    }


}
